<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2019-05-06
 * Time: 15:08
 */
namespace console\controllers;

use common\jobs\NewUserJob;
use common\models\StockBalanceHouse;
use common\models\StockProduct;
use common\models\StockWarehouse;
use common\models\Tally;
use common\models\TallyArap;
use common\models\TallyCategory;
use common\models\TallyRecord;
use common\services\TallyArapService;
use common\services\TallyStockBalanceService;
use common\services\ToolService;
use Yii;
use yii\console\Controller;

/**]
 * Class IndexController
 * @package console\controllers
 */
class IndexController extends Controller
{

    public function actionIndex()
    {
        echo 'hello cli';

        $phone = '13663002790';

        $result = ToolService::sendInviteSms($phone,['name' => '常子明']);
        print_r($result);
    }

    public function actionFreshCate()
    {
        $baseStr = include_once Yii::$app->getBasePath().'/../common/config/baseCategoryConf.php';
        $baseCateConf =  json_decode($baseStr,true);
//        print_r($baseCateConf);
        $page = 1 ;
        $limit = 10 ;
        $lastId = 0; //起始ID
        while (true) {
            $offset = $limit * ($page - 1) ;
            $tlist = Tally::find()->select('id')
                ->andFilterWhere(['>','id',$lastId])
                ->orderBy('id asc')
                ->offset($offset)
                ->limit($limit)
                ->asArray()
                ->all();
            foreach ($tlist as $tl){
                $tallyId = $tl['id'];
                // 类别新旧对应关系
                $refChange = [];
                // 先进行批量插入
                foreach ($baseCateConf as $bv) {
                    // 插入一级类目
                    $model = new TallyCategory();
                    $formData = [
                        'title' => $bv['title'],
                        'pic'   => '' ,
                        'tally_id' => $tallyId,
                        'type'  => intval($bv['type']),
                        'pid'   => 0,
                        'uid'   => 0,
                        'is_sys' => 0
                    ];
                    $model->load($formData,'');
                    $ret = $model->save();
                    if($ret){
                        // 插入二级类目
                        $newId = $model->id;
                        $refChange[] = ['old'=>$bv['id'],'new'=>$newId];
                        foreach ($bv['children'] as $bvv) {
                            $model2 = new TallyCategory();
                            $formData2 = [
                                'title' => $bvv['title'],
                                'pic'   => '' ,
                                'tally_id' => $tallyId,
                                'type'  => intval($bvv['type']),
                                'pid'   => $newId,
                                'uid'   => 0,
                                'is_sys' => 0
                            ];
                            $model2->load($formData2,'');
                            $ret2 = $model2->save();
                            if($ret2){
                                $refChange[] = ['old'=>$bvv['id'],'new'=>$model2->id];
                            }else{
                                echo '二级类别插入失败:tallyID+'.$tallyId.'.'.$bv['title'].'.'.$bvv['title'].PHP_EOL;;
                            }
                        }
                    }else{
                        // 插入类别错误
                        echo '一级类别插入失败:tallyID+'.$tallyId.'.'.$bv['title'].PHP_EOL;;
                    }
                }
                // 重新更新对应关系
                print_r($refChange);
                foreach ($refChange as $ref) {
                    // 进行Update
                    TallyCategory::updateAll(['pid' =>$ref['new']],['tally_id' => $tallyId,'pid'=>$ref['old']]);
                    TallyRecord::updateAll(['category_id' =>$ref['new']],['tally_id' => $tallyId,'category_id'=>$ref['old']]);
                    TallyRecord::updateAll(['category_pid' =>$ref['new']],['tally_id' => $tallyId,'category_pid'=>$ref['old']]);
                    echo '替换完成_old:'.$ref['old'].'-new:'.$ref['new'].PHP_EOL;
                }
            }
            $page ++ ;
        }

//        $tallyId = 42;
//        // 类别新旧对应关系
//        $refChange = [];
//        // 先进行批量插入
//        foreach ($baseCateConf as $bv) {
//            // 插入一级类目
//            $model = new TallyCategory();
//            $formData = [
//                'title' => $bv['title'],
//                'pic'   => '' ,
//                'tally_id' => $tallyId,
//                'type'  => intval($bv['type']),
//                'pid'   => 0,
//                'uid'   => 0,
//                'is_sys' => 0
//            ];
//            $model->load($formData,'');
//            $ret = $model->save();
//            if($ret){
//                // 插入二级类目
//                $newId = $model->id;
//                $refChange[] = ['old'=>$bv['id'],'new'=>$newId];
//                foreach ($bv['children'] as $bvv) {
//                    $model2 = new TallyCategory();
//                    $formData2 = [
//                        'title' => $bvv['title'],
//                        'pic'   => '' ,
//                        'tally_id' => $tallyId,
//                        'type'  => intval($bvv['type']),
//                        'pid'   => $newId,
//                        'uid'   => 0,
//                        'is_sys' => 0
//                    ];
//                    $model2->load($formData2,'');
//                    $ret2 = $model2->save();
//                    if($ret2){
//                        $refChange[] = ['old'=>$bvv['id'],'new'=>$model2->id];
//                    }else{
//                        echo '二级类别插入失败:tallyID+'.$tallyId.'.'.$bv['title'].'.'.$bvv['title'].PHP_EOL;;
//                    }
//                }
//            }else{
//                // 插入类别错误
//                echo '一级类别插入失败:tallyID+'.$tallyId.'.'.$bv['title'].PHP_EOL;;
//            }
//        }
//        // 重新更新对应关系
//        print_r($refChange);
//        foreach ($refChange as $ref) {
//            // 进行Update
//            TallyCategory::updateAll(['pid' =>$ref['new']],['tally_id' => $tallyId,'pid'=>$ref['old']]);
//            TallyRecord::updateAll(['category_id' =>$ref['new']],['tally_id' => $tallyId,'category_id'=>$ref['old']]);
//            TallyRecord::updateAll(['category_pid' =>$ref['new']],['tally_id' => $tallyId,'category_pid'=>$ref['old']]);
//            echo '替换完成_old:'.$ref['old'].'-new:'.$ref['new'].PHP_EOL;
//        }
    }

    // 账本初始化任务补偿 把uid丢到队列即可
//    public function actionTestJob()
//    {
//        // $i 是UID
//        for ($i = 1543;$i< 1595;$i++){
//            // 用户注册成功事件 写入异步队列处理
//            $a = Yii::$app->queue->push(new NewUserJob([
//                'uid' => $i,
//            ]));
//            var_dump($a);
//        }
//    }

    // 对arap记录进行重新核算
    public function actionArapCheck() {
        $list = TallyArap::find()->andFilterWhere(['>','state',TallyArap::STATE_INVALID])->all();
        foreach ($list as $lv) {
            $arapId = $lv->id;
            TallyArapService::calRelationAmount($arapId); // 应收应付统计核算
        }
    }

    // php yii index/stock-flush
    // 针对库存模块金额的重新计算
    public function actionStockFlush()
    {
        $tallyId = 15481;
        $productList = StockProduct::find()->where(['tally_id' => $tallyId])->asArray()->all();
        // 取出所有house
        $houseList = StockWarehouse::find()->where(['tally_id' => $tallyId])->asArray()->all();
        $houseListMap = [];
        foreach ($houseList as $houseInfo) {
            $houseListMap[$houseInfo['id']] = $houseInfo;
        }
        foreach ($productList as $productInfo) {
            $productId = $productInfo['id'];
            TallyStockBalanceService::syncProductBalance($tallyId,$productId,$productInfo);
            // 取出该商品涉及到的所有house
            $stocks = StockBalanceHouse::find()->select('distinct(house_id) as hid')->where([
                'tally_id' => $tallyId,
                'product_id' => $productId
            ])->asArray()->all();
            foreach ($stocks as $stock) {
                $stockId = $stock['hid'];
                if(isset($houseListMap[$stockId])) {
                    // 触发总表 仓库维度数据更新
                    TallyStockBalanceService::syncProductHouseBalance($tallyId, $stockId, $houseListMap[$stockId], $productId, $productInfo);
                }
            }
        }
    }
}
